package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RequestMapping("/edumsm/msm")
@RestController
public class MSMController {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;

    @GetMapping("send/{emailReceiver}")
    public R sendSimpleMail(@PathVariable String emailReceiver) {
        //从redis获取验证码
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String code1 = ops.get(emailReceiver);
        if (!StringUtils.isEmpty(code1)){
            return R.ok();
        }
        //获取到就发送

        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(from);
        // 设置邮件接收者
        message.setTo(emailReceiver);
        // 设置邮件的主题
        message.setSubject("登录验证码");
        // 设置邮件的正文
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code.append(r);
        }
        String toString = code.toString();
        String text = "您的验证码为：" + toString + ",请勿泄露给他人。";
        message.setText(text);
        // 发送邮件
        try {
            javaMailSender.send(message);
            ops.set(emailReceiver,toString,5, TimeUnit.MINUTES);
            return R.ok();
            //  发送成功
        } catch (MailException e) {
            e.printStackTrace();
        }
        return R.error();
    }
}

